package controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pojo.AppVersion;
import pojo.DevUser;
import service.AppInfoService;
import service.VersionService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/ver")
public class VersionController {
    @Resource
    private VersionService versionService;
    @Resource
    private AppInfoService appInfoService;

    @RequestMapping("/toAdd")
    public String toAdd(int id, Model model){
        AppVersion appVersion = new AppVersion();
        appVersion.setAppId(id);
        List<AppVersion> appVersionList = versionService.selList(id);
        model.addAttribute("appVersionList",appVersionList);
        model.addAttribute("appVersion",appVersion);
        return "/developer/appversionadd";
    }

    //新增版本
    @RequestMapping("/add")
    public String add(AppVersion appVersion, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "a_downloadLink",required = false) MultipartFile a_downloadLink){
        String downloadLink = null;
        String apkLocPath = null;
        String apkFileName = null;
        if (!a_downloadLink.isEmpty()){
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
            String oldFileName = a_downloadLink.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")){
                String apkName = null;
                try{
                    apkName = appInfoService.view(appVersion.getAppId()).getAPKName();
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (apkName==null||"".equals(apkName)){
                    return "redirect:/ver/toAdd?id="+appVersion.getAppId();
                }
                apkFileName = apkName+"-"+appVersion.getVersionNo()+".apk";
                File targetFile = new File(path,apkFileName);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try {
                    a_downloadLink.transferTo(targetFile);
                }catch (Exception e){
                    e.printStackTrace();
                    return "redirect:/ver/toAdd?id="+appVersion.getAppId();
                }
                downloadLink = request.getContextPath()+"/statics/uploadfiles"+apkFileName;
                apkLocPath = path + File.separator+apkFileName;
            }else {
                return "redirect:/ver/toAdd?id="+appVersion.getAppId();
            }
        }
        appVersion.setDownloadLink(downloadLink);
        appVersion.setApkFileName(apkFileName);
        appVersion.setApkLocPath(apkLocPath);
        DevUser devUser = (DevUser) request.getSession().getAttribute("devUserSession");
        appVersion.setCreatedBy(devUser.getId());
        int result = versionService.add(appVersion);
        if(result > 0){
            return "redirect:/dev/flatform/app/list";
        }else {
           return "redirect:/ver/toAdd?id="+appVersion.getAppId();
        }
    }
    @RequestMapping("/view")
    public String view(int vid,int aid, Model model){
        AppVersion appVersion = versionService.view(vid);
        List<AppVersion> appVersionList = versionService.selList(aid);
        model.addAttribute("appVersionList",appVersionList);
        model.addAttribute("appVersion",appVersion);
        return "/developer/appversionmodify";
    }
    //修改版本
    @RequestMapping("/update")
    public String update(AppVersion appVersion, HttpServletRequest request,
                         @RequestParam(value = "attach",required = false) MultipartFile attach) {
        if (!attach.isEmpty()) {
            String downloadLink = null;
            String apkLocPath = null;
            String apkFileName = null;
            String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")) {
                String apkName = null;
                try {
                    apkName = appInfoService.view(appVersion.getAppId()).getAPKName();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (apkName == null || "".equals(apkName)) {
                    return "redirect:/ver/view?id=" + appVersion.getAppId();
                }
                apkFileName = apkName + "-" + appVersion.getVersionNo() + ".apk";
                File targetFile = new File(path, apkFileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    return "redirect:/ver/view?id=" + appVersion.getAppId();
                }
                downloadLink = request.getContextPath() + "/statics/uploadfiles" + apkFileName;
                apkLocPath = path + File.separator + apkFileName;
                appVersion.setDownloadLink(downloadLink);
                appVersion.setApkFileName(apkFileName);
                appVersion.setApkLocPath(apkLocPath);
            } else {
                return "redirect:/ver/view?id=" + appVersion.getAppId();
            }
        }
        DevUser devUser = (DevUser) request.getSession().getAttribute("devUserSession");
        appVersion.setCreatedBy(devUser.getId());
        int result = versionService.add(appVersion);
        if (result > 0) {
            return "redirect:/dev/flatform/app/list";
        } else {
            return "redirect:/ver/view?id=" + appVersion.getAppId();
        }
    }

    //删除apk文件
    @GetMapping("/delApk")
    @ResponseBody
    public Object delApk(int id){
        AppVersion version=versionService.view(id);
        Map<String,String> map=new HashMap<>();
        File file=new File(version.getApkLocPath());
        if (file.delete()){
            map.put("result","success");
        }else {
            map.put("result","failed");
        }
        return JSON.toJSONString(map);
    }
}